package com.hk.kindheartedness;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.hk.kindheartedness.db.DBOpenHelper;
import com.hk.kindheartedness.model.User;
import com.hk.kindheartedness.util.DateUtil;
import com.hk.kindheartedness.util.ToastUtil;

import java.util.Date;
import java.util.Objects;

/**
 * 患者修改个人密码
 */
public class PatientUpdatePwdActivity extends AppCompatActivity implements View.OnClickListener {

    //    Initialize Toast
    private Toast toast;

    //    Initialize intent
    private Intent intent;

    //    声明DBOpenHelper对象
    private DBOpenHelper dbOpenHelper;

    //  Initialize button
    private Button updatePwdBtn;

    private EditText oldPwd,newPwd,newPwd2;

    private TextView phone;

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_patient_update_pwd);
//        实例化
        dbOpenHelper = new DBOpenHelper(PatientUpdatePwdActivity.this, "db_kindheartedness", null, 1);
//        获取个人信息控制权
        phone = findViewById(R.id.phone);
        oldPwd = findViewById(R.id.oldPwd);
        newPwd = findViewById(R.id.newPwd);
        newPwd2 = findViewById(R.id.newPwd2);
//        获取更新按钮控制权
        updatePwdBtn = findViewById(R.id.updatePwdBtn);
        updatePwdBtn.setOnClickListener(this);
//        提取出当前用户传递的个人信息
        Intent intent2 = getIntent();
        Bundle bundle = intent2.getExtras();
//        回显获取的个人信息
        echoPersonInfo(bundle);

    }

    /**
     * 回显传递的个人信息
     * @param bundle
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    private void echoPersonInfo(Bundle bundle) {
        if (Objects.isNull(bundle)) {
            toast = ToastUtil.toastHint(toast,PatientUpdatePwdActivity.this,"获取个人信息失败,请重试！");
            return;
        }
        String loginPhoneString = (String) bundle.get("loginPhone");
        if (Objects.nonNull(loginPhoneString)) {
//                进行回显
            phone.setText(loginPhoneString);
            return;
        }
        toast = ToastUtil.toastHint(toast,PatientUpdatePwdActivity.this,"获取个人信息失败,请重试！");
        return;
    }

    /**
     * 按钮点击事件
     * @param v
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
//            更新密码
            case R.id.updatePwdBtn:
                updatePersonPwd();
                break;
            default:
                return;
        }
    }

    /**
     * 更新当前登录账户密码
     */
    private void updatePersonPwd() {
//        获取各控件当前的值
        String phoneToStr = phone.getText().toString();
        String oldPwdToStr = oldPwd.getText().toString();
        String newPwdToStr = newPwd.getText().toString();
        String newPwd2ToStr = newPwd2.getText().toString();
//        校验密码是否正确
        Boolean check = checkPwdDate(phoneToStr,oldPwdToStr,newPwdToStr,newPwd2ToStr);
        if (check) {
            SQLiteDatabase readableDatabase = dbOpenHelper.getReadableDatabase();
//                    封装需要更新的采购员信息
            ContentValues contentValues = new ContentValues();
            contentValues.put("password",newPwdToStr);
            contentValues.put("update_time", DateUtil.dateString(new Date()));
//                    执行更新采购员信息
            int update = readableDatabase.update("user", contentValues, "phone = ?", new String[]{phoneToStr});
            if (update == 1) {
                toast = ToastUtil.toastHint(toast, PatientUpdatePwdActivity.this, "个人密码更新成功，请重新登录！");
//                跳转到登录界面
                intent = new Intent(PatientUpdatePwdActivity.this,LoginActivity.class);
                startActivity(intent);
//                关闭当前页面
                PatientUpdatePwdActivity.this.finish();
                return;
            }
            toast = ToastUtil.toastHint(toast, PatientUpdatePwdActivity.this, "个人密码更新失败，请稍后重试！");
            return;
        }

    }

    /**
     * 校验当前密码是否正确
     * @param phoneToStr 手机号
     * @param oldPwdToStr 旧密码
     * @param newPwdToStr 新密码
     * @param newPwd2ToStr 确认新密码
     * @return
     */
    private Boolean checkPwdDate(String phoneToStr,String oldPwdToStr, String newPwdToStr, String newPwd2ToStr) {
        /**
         * 1、判断所有密码是否为空
         * 2、判断旧密码是否正确
         * 3、判断新密码是否一致
         */
//        校验旧密码是否为空
        if (oldPwdToStr.equals("") || oldPwdToStr.equals(null) || oldPwdToStr == null) {
            toast = ToastUtil.toastHint(toast,PatientUpdatePwdActivity.this,"旧密码不能为空！");
            return false;
        }
//          校验新密码是否为空
        if (newPwdToStr.equals("") || newPwdToStr.equals(null) || newPwdToStr == null) {
            toast = ToastUtil.toastHint(toast,PatientUpdatePwdActivity.this,"新密码不能为空！");
            return false;
        }
        if (newPwd2ToStr.equals("") || newPwd2ToStr.equals(null) || newPwd2ToStr == null) {
            toast = ToastUtil.toastHint(toast,PatientUpdatePwdActivity.this,"确认密码不能为空！");
            return false;
        }

//        判断密码长度是否符合规则（最低长度6位）
        int oldPwdLength = oldPwdToStr.length();
        int newPwdLength = newPwdToStr.length();
        if (oldPwdLength < 6 || newPwdLength < 6) {
            toast = ToastUtil.toastHint(toast,PatientUpdatePwdActivity.this,"密码最少6位,请重新输入！");
            return false;
        }

//        判断旧密码是否存在
        SQLiteDatabase readableDatabase = dbOpenHelper.getReadableDatabase();
        Cursor queryUser = readableDatabase.query("user", null, "phone = ? and password = ? ", new String[]{phoneToStr, oldPwdToStr}, null, null, null);
        String userId = null;
        while (queryUser.moveToNext()) {
            userId = queryUser.getString(0);
        }
        if (userId == null) {
            toast = ToastUtil.toastHint(toast,PatientUpdatePwdActivity.this,"旧密码输入错误,请重新输入！");
            return false;
        }
//        判断新密码是否一致
        if (!newPwdToStr.equals(newPwd2ToStr)) {
            toast = ToastUtil.toastHint(toast,PatientUpdatePwdActivity.this,"新密码输入不一致,请检查！");
            return false;
        }
//       判断新旧密码是否一致
        if (oldPwdToStr.equals(newPwdToStr)) {
            toast = ToastUtil.toastHint(toast,PatientUpdatePwdActivity.this,"新密码不能为旧密码,请重新输入！");
            return false;
        }
        return true;
    }

    /**
     * 断开数据库连接
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (dbOpenHelper != null) {
            dbOpenHelper.close();
        }
    }

}